package com.hnucm.chapter2_4;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class BinderPoolActivity extends AppCompatActivity {

    private static final String TAG = "BinderPoolActivity";

    private ISecurityCenter mSecurityCenter;
    private ICompute mCompute;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //在子线程中连接远程Service 回顾一下客户端的主线程不要调用服务端的方法，有可能是耗时操作，所以最好在子线程中运行
        new Thread(() -> doWork()).start();
    }

    private void doWork() {
        //创建Binder池实例
        BinderPool binderPool = BinderPool.getInsance(BinderPoolActivity.this);
        //Binder池调用queryBinder方法统一拿到不同的业务请求转发给远程Service中
        IBinder securityBinder = binderPool.queryBinder(BinderPool.BINDER_SECURITY_CENTER);//调用queryBinder方法
        mSecurityCenter = (ISecurityCenter) SecurityCenterImpl.asInterface(securityBinder);
        Log.d(TAG, "visit ISecurityCenter");
        String msg = "hello world-安卓";
        Log.d(TAG, "doWork content:" + msg);
        try {
            //执行加密操作
            String password = mSecurityCenter.encrypt(msg);
            Log.d(TAG, "doWork: encrypt:" + password);
            Log.d(TAG, "doWork: decrypt:" + mSecurityCenter.decrypt(password));
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        Log.d(TAG, "visit ICompute");
        //Binder池调用queryBinder方法统一拿到不同的业务请求转发给远程Service中
        IBinder computeBinder = binderPool.queryBinder(BinderPool.BINDER_COMPUTE);//调用queryBinder方法
        mCompute = ComputeImpl.asInterface(computeBinder);
        try {
            Log.d(TAG, "doWork: 3+5=" + mCompute.add(3, 5));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}